﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BiocityFilmquizAdmin.Src;
using BiocityFilmquizAdmin.Src.DatabaseAccess;
using BiocityFilmquizAdmin.Src.Domain;
using BiocityFilmquizAdmin.Src.ftp;

namespace BiocityFilmquizAdmin
{
    public partial class About : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            resetLabels();
            if (Session["loggedIn"] != null && (bool)Session["loggedIn"])
            {
                renderImagesAndAnswers();
                renderExtrasAndAnswers();
            }

        }

        private void Page_PreRender(object sender, System.EventArgs e)
        {
            renderLoggedInBoxes();
        }

        private void renderLoggedInBoxes()
        {
            if (Session["loggedIn"] != null && (bool)Session["loggedIn"])
            {
                loggedInDiv.Visible = true;
                notLoggedInDiv.Visible = false;

                doIfLoggedIn();
            }
            else
            {
                loggedInDiv.Visible = false;
                notLoggedInDiv.Visible = true;
            }
        }

        private void resetLabels()
        {
            numberOfImagesLabel.Text = "";
            endDateLabel.Text = "";
        }

        private void populateRoundDropDown()
        {
            List<Round> rounds = AdminHelper.getInstance().getAllRounds();

            if (rounds.Count() != roundDropDown.Items.Count)
            {
                roundDropDown.Items.Clear();
                foreach (var round in rounds)
                {
                    roundDropDown.Items.Add(round.roundId.ToString());
                }

            }
        }

        private void doIfLoggedIn()
        {
            populateRoundDropDown();
            updateCalendars();

            renderImagesAndAnswers();
            renderExtrasAndAnswers();
        }

        private void updateCalendars()
        {
            List<Round> rounds = AdminHelper.getInstance().getAllRounds();

            String selected = roundDropDown.SelectedValue;

            Round round = AdminHelper.getInstance().getRoundById(Int32.Parse(selected));

            endCalendar.SelectedDate = round.end;

            endDateLabel.Text = round.end.ToString("yyyy-MM-dd");
        }

        protected void createNewRound_Click(object sender, EventArgs e)
        {
            int numberOfRounds = AdminHelper.getInstance().getAllRounds().Count;

            AdminHelper.getInstance().createNewRound(numberOfRounds + 1, DateTime.Now);
        }

        private void renderImagesAndAnswers()
        {
            if (roundDropDown.SelectedValue != "")
            {
                imagesPlaceholder.Controls.Clear();

                int selected = Int32.Parse(roundDropDown.SelectedValue);
                int numberOfImages = FtpHelper.getInstance().getNumberOfImages(selected);

                numberOfImagesLabel.Text = "" + numberOfImages;

                for (int i = 1; i <= numberOfImages; i++)
                {
                    Image img = new Image();
                    img.ImageUrl = Statics.getInstance().getImageBaseUrl() + "/" + selected + "/" + i + ".jpg";
                    img.CssClass = "previewImages";

                    imagesPlaceholder.Controls.Add(img);

                    imagesPlaceholder.Controls.Add(new Literal { Text = "<div class='imageAnswersContainer'>" });

                    List<string> answers = AdminHelper.getInstance().getAllAnswersForQuestion(i,
                                                                                              Int32.Parse(
                                                                                                  roundDropDown.
                                                                                                      SelectedValue));
                    foreach (string answer in answers)
                    {
                        imagesPlaceholder.Controls.Add(new Label { Text = answer });

                        imagesPlaceholder.Controls.Add(new Literal() { Text = "<span>" });

                        LinkButton linkbutton = new LinkButton();
                        linkbutton.Click += deleteAnswerClick;
                        linkbutton.ID = answer + "-" + i;
                        linkbutton.Text = "Slet svarmulighed";
                        linkbutton.CssClass = "deleteAnswerLink";

                        imagesPlaceholder.Controls.Add(linkbutton);

                        imagesPlaceholder.Controls.Add(new Literal() { Text = "</span>" });

                        imagesPlaceholder.Controls.Add(new Literal { Text = "<br />" });
                    }

                    if (answers.Count == 0)
                    {
                        Button deleteImageButton = new Button();
                        deleteImageButton.Text = "Slet billedet";
                        deleteImageButton.Click += deleteImageClick;
                        deleteImageButton.ID = "deleteImageButton" + i;
                        deleteImageButton.CssClass = "addAnswerButton";

                        imagesPlaceholder.Controls.Add(deleteImageButton);

                        imagesPlaceholder.Controls.Add(new Literal() { Text = "<br />" });
                    }

                    Panel panel = new Panel();
                    panel.DefaultButton = "button" + i;
                    imagesPlaceholder.Controls.Add(panel);

                    TextBox textBox = new TextBox();
                    textBox.ID = "textBox" + i;
                    panel.Controls.Add(textBox);

                    Button button = new Button();
                    button.Text = "Tilføj svarmulighed";
                    button.Click += newAnswerButton_Click;
                    button.ID = "button" + i;
                    button.CssClass = "addAnswerButton";

                    panel.Controls.Add(button);

                    imagesPlaceholder.Controls.Add(new Literal { Text = "</div>" });

                    imagesPlaceholder.Controls.Add(new Literal { Text = "<hr class='imageSeperators' />" });
                }
            }
        }

        protected void deleteAnswerClick(object sender, EventArgs e)
        {
            List<string> ids = ((LinkButton)sender).ID.Split('-').ToList();

            AdminHelper.getInstance().deleteAnswer(ids[0], Int32.Parse(ids[1]), Int32.Parse(roundDropDown.SelectedValue));
        }

        protected void deleteImageClick(object sender, EventArgs e)
        {
            string buttonNumber = ((Button)sender).ID.Replace("deleteImageButton", "");
            int buttonPushed = Int32.Parse(buttonNumber);

            FtpHelper.getInstance().deleteFileFromFtp(Int32.Parse(roundDropDown.SelectedValue), buttonPushed);
            AdminHelper.getInstance().deleteMovieInfo(buttonPushed, Int32.Parse(roundDropDown.SelectedValue));
        }

        protected void uploadButton_Click(object sender, EventArgs e)
        {
            uploadNewImageToFtp();
        }

        protected void uploadExtraButton_Click(object sender, EventArgs e)
        {
            uploadNewExtraToFtp();
        }

        protected void newAnswerButton_Click(object sender, EventArgs e)
        {
            string buttonNumber = ((Button)sender).ID.Replace("button", "");
            int buttonPushed = Int32.Parse(buttonNumber);
            TextBox textBox = (TextBox)imagesPlaceholder.FindControl("textBox" + buttonPushed);

            AdminHelper.getInstance().insertNewAnswer(textBox.Text, buttonPushed, Int32.Parse(roundDropDown.SelectedValue));
        }

        private void uploadNewImageToFtp()
        {
            int numberOfImages = FtpHelper.getInstance().getNumberOfImages(Int32.Parse(roundDropDown.SelectedValue));
            string filePath = Server.MapPath("/tempUpload/" + (numberOfImages + 1) + ".jpg");

            fileUpload.PostedFile.SaveAs(filePath);

            string result = "Der skete en fejl under upload";

            result = FtpHelper.getInstance().UploadFile(filePath, Int32.Parse(roundDropDown.SelectedValue));

            resultLabel.Text = result;

            File.Delete(filePath);
        }

        private void uploadNewExtraToFtp()
        {
            int numberOfExtras = FtpHelper.getInstance().getNumberOfExtras(Int32.Parse(roundDropDown.SelectedValue));
            string filePath = Server.MapPath("/tempUpload/" + (numberOfExtras + 1) + ".mp3");

            extraUpload.PostedFile.SaveAs(filePath);

            FtpHelper.getInstance().UploadExtraFile(filePath, Int32.Parse(roundDropDown.SelectedValue));

            File.Delete(filePath);
        }

        protected void endCalendar_SelectionChanged(object sender, EventArgs e)
        {
            AdminHelper.getInstance().updateEndDateOnRound(Int32.Parse(roundDropDown.SelectedValue), endCalendar.SelectedDate);
        }

        private void renderExtrasAndAnswers()
        {
            if (roundDropDown.SelectedValue != "")
            {
                extraPlaceholder.Controls.Clear();

                int selected = Int32.Parse(roundDropDown.SelectedValue);
                int numberOfExtras = FtpHelper.getInstance().getNumberOfExtras(selected);

                for (int i = 1; i <= numberOfExtras; i++)
                {
                    HyperLink hpl = new HyperLink();
                    hpl.NavigateUrl = Statics.getInstance().getImageBaseUrl() + "/" + selected + "-extra/" + i + ".mp3";
                    hpl.CssClass = "extraLink";

                    extraPlaceholder.Controls.Add(hpl);

                    extraPlaceholder.Controls.Add(new Literal { Text = "<div class='imageAnswersContainer'>" });


                    List<string> answers = AdminHelper.getInstance().getAllAnswersForExtra(i,
                                                                                              Int32.Parse(
                                                                                                  roundDropDown.
                                                                                                      SelectedValue));
                    foreach (string answer in answers)
                    {
                        extraPlaceholder.Controls.Add(new Label { Text = answer });

                        extraPlaceholder.Controls.Add(new Literal() { Text = "<span>" });

                        LinkButton linkbutton = new LinkButton();
                        linkbutton.Click += deleteExtraAnswerClick;
                        linkbutton.ID = answer + "-" + i;
                        linkbutton.Text = "Slet svarmulighed";
                        linkbutton.CssClass = "deleteAnswerLink";

                        extraPlaceholder.Controls.Add(linkbutton);

                        extraPlaceholder.Controls.Add(new Literal() { Text = "</span>" });

                        extraPlaceholder.Controls.Add(new Literal { Text = "<br />" });
                    }

                    if (answers.Count == 0)
                    {
                        Button deleteExtraButton = new Button();
                        deleteExtraButton.Text = "Slet Ekstra spørgsmålet";
                        deleteExtraButton.Click += deleteExtraClick;
                        deleteExtraButton.ID = "deleteExtraButton" + i;
                        deleteExtraButton.CssClass = "addAnswerButton";

                        extraPlaceholder.Controls.Add(deleteExtraButton);

                        extraPlaceholder.Controls.Add(new Literal() { Text = "<br />" });
                    }

                    Panel panel = new Panel();
                    panel.DefaultButton = "extraButton" + i;
                    extraPlaceholder.Controls.Add(panel);

                    TextBox textBox = new TextBox();
                    textBox.ID = "extraTextBox" + i;
                    panel.Controls.Add(textBox);

                    Button button = new Button();
                    button.Text = "Tilføj svarmulighed";
                    button.Click += newExtraAnswerButton_Click;
                    button.ID = "extraButton" + i;
                    button.CssClass = "addAnswerButton";

                    panel.Controls.Add(button);

                    extraPlaceholder.Controls.Add(new Literal { Text = "</div>" });
                    extraPlaceholder.Controls.Add(new Literal { Text = "<br />" });
                    extraPlaceholder.Controls.Add(new Literal { Text = "<br />" });

                    extraPlaceholder.Controls.Add(new Literal() { Text = "Hvor mange spørgsmål skal besvares før ekstraspørgsmål frigives? (Gemmes sammen med første svarmulighed)." });
                    extraPlaceholder.Controls.Add(new Literal { Text = "<br />" });
                    TextBox tb = new TextBox();
                    tb.ID = "releasedAt" + i;
                    int releasedAt = AdminHelper.getInstance().getReleasedAt(i, selected);
                    if (releasedAt != -1)
                    {
                        tb.Text = "" + releasedAt;
                    }

                    extraPlaceholder.Controls.Add(tb);

                    extraPlaceholder.Controls.Add(new Literal { Text = "<hr class='imageSeperators' />" });
                }
            }
        }

        protected void deleteExtraAnswerClick(object sender, EventArgs e)
        {
            List<string> ids = ((LinkButton)sender).ID.Split('-').ToList();

            AdminHelper.getInstance().deleteExtraAnswer(ids[0], Int32.Parse(ids[1]), Int32.Parse(roundDropDown.SelectedValue));
        }

        protected void deleteExtraClick(object sender, EventArgs e)
        {
            string buttonNumber = ((Button)sender).ID.Replace("deleteExtraButton", "");
            int buttonPushed = Int32.Parse(buttonNumber);

            FtpHelper.getInstance().deleteExtraFromFtp(Int32.Parse(roundDropDown.SelectedValue), buttonPushed);
            AdminHelper.getInstance().deleteMovieInfo(buttonPushed + 900, Int32.Parse(roundDropDown.SelectedValue));
        }

        protected void newExtraAnswerButton_Click(object sender, EventArgs e)
        {
            string buttonNumber = ((Button)sender).ID.Replace("extraButton", "");
            int buttonPushed = Int32.Parse(buttonNumber);
            TextBox textBox = (TextBox)extraPlaceholder.FindControl("extraTextBox" + buttonPushed);
            TextBox textBoxReleased = (TextBox)extraPlaceholder.FindControl("releasedAt" + buttonPushed);

            AdminHelper.getInstance().insertNewExtraAnswer(textBox.Text, buttonPushed, Int32.Parse(roundDropDown.SelectedValue), Int32.Parse(textBoxReleased.Text));
        }

    }
}
